/*
 * Copyright 2008 Georgi Staykov
 * 
 * This file is part of pscoder.
 *
 * pscoder is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * pscoder is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with pscoder.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.gstaykov.pscoder.editor.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.handlers.HandlerUtil;

import com.gstaykov.pscoder.editor.completion.CompletionDictionary;
import com.gstaykov.pscoder.util.Logger;

public class RebuildCADHandler extends AbstractHandler {

    private Logger logger = Logger.getInstance();
    
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IEditorPart editor = HandlerUtil.getActiveEditor(event);
        IEditorInput editorInput = editor.getEditorInput();
        if ((editorInput != null) && (editorInput instanceof IPathEditorInput)) {
            IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(((IPathEditorInput)editorInput).getPath());
            // if more than 1 file matches return null because it is not clear which file is wanted
            IFile file = (files.length == 1)? files[0] : null;
            
            if (file != null) {
                logger.logInfo("Rebuilding dictionary for project: " + file.getProject().getName());
                try {
                    CompletionDictionary.getInstance(file.getProject().getName()).rebuildDictionary();
                } catch (CoreException e) {
                    logger.logError("An error has occured while rebuilding dictionary for project: " + file.getProject().getName(), e);
                }
            }
        }
        return null;
    }
}
